package com.it.gw.modules.water.adapter

import android.annotation.SuppressLint
import android.content.Context
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.it.common.utils.GlideUtils
import com.it.common.utils.isNotEmpty
import com.it.gw.R
import com.it.gw.data.PhotoBean
import com.it.gw.databinding.ItemPhotoSelectBinding


class SelectPhotoAdapter(
    var context: Context,
    var listener: ((Int) -> Unit)? = null,
    var close: ((Int) -> Unit)? = null,
    var datas: List<PhotoBean>
) : RecyclerView.Adapter<SelectPhotoAdapter.ViewHolder>() {
    companion object {
        const val TAG = "SelectPhotoAdapter"
    }

    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): ViewHolder {
        val binding = ItemPhotoSelectBinding.inflate(LayoutInflater.from(parent.context))
        return ViewHolder(binding)
    }


    override fun onBindViewHolder(holder: ViewHolder, @SuppressLint("RecyclerView") position: Int) {
        val data = datas[position]

        if (data.id.isNotEmpty() && data.url.isNotEmpty()) {
            GlideUtils.loadNet(
                context,
                data.url!!,
                holder.binding.imageView,
                defaultRes = R.drawable.default_pic,
                errorRes = R.drawable.default_pic
            )
            holder.binding.ivClose.visibility = View.VISIBLE
        } else {
            if (TextUtils.isEmpty(data.filePath)) {
                holder.binding.imageView.setImageResource(R.drawable.bg_add_imgs)
                holder.binding.ivClose.visibility = View.GONE

            } else {
                GlideUtils.loadFile(context, data.filePath!!, holder.binding.imageView)
                holder.binding.ivClose.visibility = View.VISIBLE
            }
        }


        holder.binding.root.setOnClickListener {
            listener?.invoke(position)
        }
        holder.binding.ivClose.setOnClickListener {
            close?.invoke(position)
        }


    }

    override fun getItemCount() = datas.size

    class ViewHolder(val binding: ItemPhotoSelectBinding) :
        RecyclerView.ViewHolder(binding.root)
}